<template>
  <el-upload
    :file-list="fileList"
    action="/api/uploadImg"
    list-type="picture-card"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from "vue"
import { Plus } from "@element-plus/icons-vue"
import { UploadFile, UploadFiles, UploadProps } from "element-plus"
import { getBasePath } from "@/api/common"
const basePath = ref("")
onMounted(async () => {
  const { data } = await getBasePath()
  basePath.value = data
})
const props = defineProps({
  btnText: {
    type: String,
    default: "上传图片"
  },
  tip: {
    type: String,
    default: "图片不能超过 2M."
  },
  modelValue: {
    default: () => [],
    type: Array
  }
})
const fileList = computed(() => {
  console.log(props.modelValue)

  return props.modelValue.map((item: any) => {
    return {
      name: item.name,
      url: basePath.value + item.url
    }
  })
})

const dialogImageUrl = ref("")
const dialogVisible = ref(false)
const emit = defineEmits(["update:modelValue"])

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  const fileList: any[] = uploadFiles.map((item: any) => {
    return {
      name: item.name,
      url: item.response?.data || item.url.split(basePath.value).at("-1")
    }
  })

  emit("update:modelValue", fileList)
}
const handleSuccess: UploadProps["onSuccess"] = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log(uploadFiles)

  const fileList: any[] = uploadFiles.map((item: any) => {
    return {
      name: item.name,
      url: item.response?.data || item.url.split(basePath.value).at("-1")
    }
  })
  console.log(fileList)

  emit("update:modelValue", fileList)
}
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
</script>
